﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1_TwoSum
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = new int[] { 2, 7, 11, 15 };
            int target = 9;

            int[] result = TwoSum_WZ(nums, target);

            foreach(int item in result)
            { 
                Console.WriteLine(item.ToString());
            }

            Console.ReadLine();
        }

        public static int[] TwoSum(int[] nums, int target)
        {
            for (int i = 0; i < nums.Length; i++)
            {
                for (int j = i + 1; j < nums.Length; j++)
                {
                    if (target == nums[i] + nums[j])
                    {
                        return new int[] { i, j };
                    }
                }
            }

            return null;
        }

        public static int[] TwoSum_WZ(int[] nums, int target)
        {
            int[] result = new int[2];

            Dictionary<int, int> dic = nums.Select((value,index) => new { value, index }).ToDictionary(key => key.value, value => value.index);

            for (int i = 0; i < nums.Length; i++)
            {
                int v2 = target - nums[i];
                if (dic.ContainsKey(v2))
                {
                    result[0] = i;
                    result[1] = dic[v2];
                    break;
                }
            }

            return result;
        }
    }
}
